package demo;


import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.HashSet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rongji.dfish.ui.layout.HorizontalLayout;
import com.rongji.dfish.ui.layout.View;
import com.rongji.dfish.ui.widget.TreeItem;
import com.rongji.dfish.ui.widget.TreePanel;
//import com.rongji.dfish.xmltmpl3.widget.SourcePanel;

public class DemoServlet extends javax.servlet.http.HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		View view=getView();
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Content-Type", "text/javascript; charset=UTF-8");
		ServletOutputStream stream=resp.getOutputStream();
		stream.write(view.asJson().getBytes("UTF-8"));
		stream.close();
		System.out.println(view.formatString());
	}
	

	private View getView() {
		String rooPath=this.getServletContext().getRealPath("/test");
		View view=new View();
		HorizontalLayout root=new HorizontalLayout("r");
		view.setNode(root);
		TreePanel tree=new TreePanel("f_tree");
		root.add(tree,"35%");
		setData(rooPath,tree);
		//tree.setDefaultValue(TreeItem.KEY_ON_CONTEXT_MENU, "VM(this).cmd('openMenu','$id')");
		View main=new View();
		main.setId("f_main");
		main.setSrc("vm:|test/panel/TreePanel.txt");
		root.add(main,"*");
		main.setHeight("*");
		return view;
	}
	private void setData(String rootPath,TreePanel tree) {
		if(rootPath.endsWith("/")||rootPath.endsWith("\\")){
			rootPath=rootPath.substring(0,rootPath.length()-1);
		}
		File root=new File(rootPath);
		for(File f : root.listFiles()){
			TreeItem node=new TreeItem();
			node.setId(f.getAbsolutePath());
			node.setText( f.getName());
			String path=f.getAbsolutePath().substring(rootPath.length());
			if(f.isFile()){
				node.setOn(TreeItem.EVENT_CLICK, "VM(this).find('f_main').reload('vm:|test/"+path+"')");
				node.setIcon("%img%/file.png");
			}else if(f.isDirectory()){
				node.setIcon( "%img%/folder.png");
				node.setOpen(true);
				setData(rootPath,f, node);
			}
			tree.addTreeItem(node);
		}
		
	}

	private void setData(String rootPath, File root, TreeItem tree) {
		for(File f : root.listFiles()){
			TreeItem node=new TreeItem();
			node.setId( f.getAbsolutePath().replace('\\', '/'));
			node.setText(f.getName());
			String path=f.getAbsolutePath().substring(rootPath.length()).replace('\\', '/');
			if(f.isFile()){
				node.setOn(TreeItem.EVENT_CLICK, "VM(this).find('f_main').reload('vm:|test"+path+"')");
				node.setIcon("%img%/file.png");
			}else if(f.isDirectory()){
				node.setIcon( "%img%/folder.png");
				setData(rootPath,f, node);
			}
			tree.addTreeItem(node);
		}
	}

}
